/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet.asynctasks;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.jaal.movilconsultanet.Progreso;
import com.jaal.movilconsultanet.R;
import com.jaal.movilconsultanet.Util;
import com.jaal.movilconsultanet.XMLContent;
import com.jaal.movilconsultanet.activities.Consulta;

public class PerfilRequester extends AsyncTask<String, Progreso, Boolean> {

	Consulta mainActivity;
	ProgressDialog progreso;
	Progreso progresoInfo = new Progreso();
	private String sessionId = null;
	String numero, password, codTlf;

	public PerfilRequester(Consulta mainActivity) {

		this.mainActivity = mainActivity;

	}

	@Override
	protected void onPreExecute() {
		progreso = new ProgressDialog(mainActivity);
		progreso.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progreso.setProgress(0);
		progreso.setMessage(mainActivity.getResources().getText(R.string.connection_connecting_server));
		progreso.setCancelable(false);
		progreso.show();
	}


	@Override
	protected Boolean doInBackground(String... urls) {

		Log.d("MCN", "GSMSessionStarter - inicio");
		// le paso el captcha cuando hago claseAsync.execute(captcha)
		sessionId = urls[0];
		HttpURLConnection connection = null;

		progresoInfo.setProgreso(10);
		progresoInfo.setMensaje(mainActivity,R.string.session_verifying);
		publishProgress(progresoInfo);

		String targetURL = "http://www.movilnet.com.ve/agl/gsm/usuario/perfilCliente.action";
		connection = null;
		URL url = null;

		try {
			// Create connection
			url = new URL(targetURL);

			progresoInfo.setProgreso(20);
			progresoInfo.setMensaje(mainActivity,R.string.connection_connecting);
			publishProgress(progresoInfo);

			Log.d("MCN", "getUsuarioPerfil - conectando..." + targetURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Cookie", sessionId);

			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			connection.setConnectTimeout(5000);

			Log.d("MCN", "getUsuarioPerfil - getting response...");
			progresoInfo.setProgreso(55);
			progresoInfo.setMensaje(mainActivity,R.string.connection_response_get);
			publishProgress(progresoInfo);

			Map<String, List<String>> mapa = connection.getHeaderFields();

			Set<String> set = mapa.keySet();

			for (String string : set) {
				Log.d("MCN", "getUsuarioPerfil - headers..." + string+" : "+mapa.get(string));
			}

			String loc = connection.getHeaderField("content-location");

			if (loc != null && loc.equalsIgnoreCase("/error.jsp")) {

				progresoInfo.setError(true);
				progresoInfo.setMensaje(mainActivity,R.string.session_expired);
				publishProgress(progresoInfo);

				return false;
			}

			// Get Response
			InputStream is = connection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuilder response = new StringBuilder();

			// bytes que ignoro para mejorar eficiencia
			rd.skip(1235);

			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
				Log.d("MCN", "getUsuarioPerfil - response: " + line);
			}

			rd.close();
			// inicializo las variables que contendran los valores para los
			// regex
			StringBuilder parentRegExp = new StringBuilder();
			StringBuilder childRegExp = new StringBuilder();
			StringBuilder texto = new StringBuilder();
			// TextView perfilTxt = null;

			// para generar el xml
			String contenido = "perfil";
			HashMap<String, String> data = new HashMap<String, String>();


			progresoInfo.setProgreso(60);
			progresoInfo.setMensaje(mainActivity,R.string.profile_getting);

			publishProgress(progresoInfo);
			// Obtengo el Numero
			parentRegExp.append("M&oacute;vil(.*?\\>){3}\\d+");
			childRegExp.append("\\d+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("movil", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put movil: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_number);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(65);
			publishProgress(progresoInfo);
			// Obtengo el Cliente
			parentRegExp.append("Cliente(.*?\\>){3}[\\s\\w]+");
			childRegExp.append("[\\w\\s]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("cliente", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put cliente: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_client);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(70);
			publishProgress(progresoInfo);
			// Obtengo la cédula
			parentRegExp.append("C&eacute;dula(.*?\\>){3}[\\d]+");
			childRegExp.append("[\\d]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("cedula", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put cedula: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_identification);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(75);
			publishProgress(progresoInfo);
			// Obtengo el estado de la línea
			parentRegExp
			.append("Estatus de la l&iacute;nea(.*?\\>){3}[\\s\\w]+");
			childRegExp.append("[\\s\\w]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("estatus", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put estatus: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_status);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(80);
			publishProgress(progresoInfo);
			// Obtengo el plan
			parentRegExp.append("Plan Actual(.*?\\>){3}[\\s\\w-]+");
			childRegExp.append("[\\s\\w-]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("plan", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put plan: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_plan);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(85);
			publishProgress(progresoInfo);
			// Obtengo el tipo de equipo
			parentRegExp.append("Tipo de Equipo(.*?\\>){3}[\\s\\w]+");
			childRegExp.append("[\\s\\w]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("tipo_equipo", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put tipoEquipo: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_deviceType);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(90);
			publishProgress(progresoInfo);
			// Obtengo el modelo de teléfono
			parentRegExp
			.append("Modelo de Tel&eacute;fono(.*?\\>){3}[\\s\\w]+");
			childRegExp.append("[\\s\\w]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("modelo_telefono", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put modeloTelefono: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_model);
			// perfilTxt.setText(texto);

			// limpio los StringBuilders
			parentRegExp.delete(0, parentRegExp.length());
			childRegExp.delete(0, childRegExp.length());
			texto.delete(0, texto.length());

			progresoInfo.setProgreso(95);
			publishProgress(progresoInfo);
			// Obtengo la descripción del teléfono
			parentRegExp
			.append("Descripci&oacute;n del Tel&eacute;fono(.*?\\>){3}[\\s\\w]+");
			childRegExp.append("[\\s\\w]+$");
			texto.append(Util.getRegExp(response, parentRegExp, childRegExp));

			data.put("descripcion", texto.toString());

			Log.d("MCN", "getUsuarioPerfil - put descripcion: " + data);

			// perfilTxt = (TextView)
			// mainActivity.findViewById(R.id.profile_description);
			// perfilTxt.setText(texto);

			XMLContent.saveXML(contenido, data);


			progresoInfo.setProgreso(100);
			progresoInfo.setMensaje(mainActivity,R.string.profile_got);
			progresoInfo.setFinished(true);
			publishProgress(progresoInfo);

		} catch (ConnectException e) {
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error);
			publishProgress(progresoInfo);
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo
			.setMensaje(mainActivity,R.string.connection_error_server);
			publishProgress(progresoInfo);
		} catch (IOException e) {
			e.printStackTrace();
			progresoInfo.setError(true);
			progresoInfo.setMensaje(mainActivity,R.string.connection_error_io);
			publishProgress(progresoInfo);
		} finally {
			if (connection != null) {
				Log.d("MCN", "CaptchaRequester - desconectando...");
				connection.disconnect();
			}
		}

		return true;
	}

	@Override
	protected void onProgressUpdate(Progreso... values) {

		Progreso mProgresoInfo = values[0];

		if (!mProgresoInfo.isError()) {
			progreso.setProgress(mProgresoInfo.getProgreso());
			progreso.setMessage(mProgresoInfo.getMensaje());

			if (mProgresoInfo.isFinished()) {
				progreso.dismiss();
			}

		} else {
			progreso.dismiss();
			Toast.makeText(mainActivity, mProgresoInfo.getMensaje(),
					Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onPostExecute(Boolean result) {

		if (progresoInfo.isError()) {

			if (!result) {

				AlertDialog.Builder builder = new AlertDialog.Builder(mainActivity);
				builder.setMessage(R.string.session_expired_msg)
				.setCancelable(false)
				.setIcon(R.drawable.ic_dialog_alert)
				.setPositiveButton(R.string.session_restart, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						new GSMSessionRestorer(mainActivity).execute("");
					}
				})
				.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();

			}	
			return;
		}
		mainActivity.refrescarPerfil();
	}

}
